package com.zany.tree.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;


import com.zany.tree.service.TreeService;
import com.zany.tree.vo.OrgInfoVO;
import com.zany.util.action.AbstractActionSupport;
import com.zany.util.action.SessionInfo;
import com.zany.util.ajax.AjaxTools;

public class OrgTreeAction extends AbstractActionSupport {

	private static final long serialVersionUID = 7195266842418172990L;
	private static Log logger = LogFactory.getLog(OrgTreeAction.class);
	private List<OrgInfoVO> orgListTemp = new ArrayList<OrgInfoVO>();
	private List<OrgInfoVO> orgList = new ArrayList<OrgInfoVO>();
	private TreeService treeService;
	
	public void getAllTree() throws Exception{
		if(logger.isInfoEnabled()){logger.info("OrgTreeAction.getTree()");}
		response = ServletActionContext.getResponse();
		orgListTemp = treeService.getAllTreeNode();
		String orgCode = request.getParameter("node");
		if(orgCode!=null && !orgCode.trim().equals("0")){
			orgList = getDownOrg(orgCode.trim());
		}else{
			orgList = getOrg();
		}
		String listNode = "[";
		for(OrgInfoVO orgVO:orgList){
			listNode += "{id:'"+orgVO.getOrgCode()+"',text:'"+orgVO.getOrgName()+"'"+(orgVO.getIsBottom().equals("1")?",leaf:true":"")+"},";
		}
		listNode = listNode.substring(0,listNode.length()-1) + "]";
		AjaxTools.exAjax(listNode,response);
	}

	public List<OrgInfoVO> getDownOrg(String orgCode){
		List<OrgInfoVO> list = new ArrayList<OrgInfoVO>();
		for(OrgInfoVO orgVO:orgListTemp){
			if(orgVO.getParentOrg().equals(orgCode)){
				list.add(orgVO);
			}
		}
		return list;
	}
	
	public List<OrgInfoVO> getOrg() throws Exception{
		List<OrgInfoVO> list = new ArrayList<OrgInfoVO>();
		String userOrg = SessionInfo.getUserOrg(request);
		for(OrgInfoVO orgVO:orgListTemp){
			if(orgVO.getOrgCode().equals(userOrg)){
				list.add(orgVO);
			}
		}
		return list;
	}
	public void getUserTree(){
		
	}
	public TreeService getTreeService() {
		return treeService;
	}

	public void setTreeService(TreeService treeService) {
		this.treeService = treeService;
	}

	public void setSession(Map arg0) {
		// TODO Auto-generated method stub
		
	}

}
